package com.jic.market.controller.manage;

import com.jic.market.common.util.ResourceLoader;
import com.jic.market.enums.ResourceEnum;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * description: ResourceController
 * date: 2020/3/12 16:29
 * author: wangys
 * version: 1.0
 */
@RestController
@RequestMapping("resource")
public class ResourceController {

    @GetMapping(value = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam String key) throws IOException {
        final ResourceEnum resourceEnum = ResourceEnum.find(key);
        if (resourceEnum == null) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        String fileName = resourceEnum.getName();
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes(), "UTF-8");
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try (OutputStream out = response.getOutputStream()) {
            try (InputStream is = ResourceLoader.loadDownloadResource(resourceEnum).getInputStream()) {
                BufferedInputStream br = new BufferedInputStream(is);
                byte[] buf = new byte[1024];
                int len = 0;
                while ((len = br.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                br.close();
                out.flush();
            }
        }
    }
}
